/**
 * webSocket 封装
 */
layui.define(function (exports) {

    //  webSocket 封装
    var $ = layui.jquery,
        websocket = function (options) {
            var defaults = {
                domain: top.location.hostname,
                port: 3398,
                protocol: ""
            };
            var opts = $.extend(defaults, options);
            var szServer = "ws://" + opts.domain + ":" + opts.port + "/" + opts.protocol;
            var socket = null;
            var bOpen = false;
            var messageEvent = {
                onInit: function () {
                    if (!("WebSocket" in window) && !("MozWebSocket" in window)) {
                        return false;
                    }
                    if (("MozWebSocket" in window)) {
                        socket = new MozWebSocket(szServer);
                    } else {
                        socket = new WebSocket(szServer);
                    }
                    if (opts.onInit) {
                        opts.onInit();
                    }
                },
                onOpen: function (event) {
                    bOpen = true;
                    if (opts.onOpen) {
                        opts.onOpen(event);
                    }
                },
                onSend: function (msg) {
                    if (opts.onSend) {
                        opts.onSend(msg);
                    }
                    socket.send(msg);
                },
                onMessage: function (msg) {
                    if (opts.onMessage) {
                        opts.onMessage(msg.data);
                    }
                },
                onError: function (event) {
                    if (opts.onError) {
                        opts.onError(event);
                    }
                },
                onClose: function (event) {
                    if (opts.onclose) {
                        opts.onclose(event);
                    }
                    if (socket.close() != null) {
                        socket = null;
                    }
                }
            };

            messageEvent.onInit();
            socket.onopen = messageEvent.onOpen;
            socket.onmessage = messageEvent.onMessage;
            socket.onerror = messageEvent.onError;
            socket.onclose = messageEvent.onClose;

            this.send = function (pData) {
                if (bOpen == false) {
                    return false;
                }
                messageEvent.onSend(pData);
                return true;
            }
            this.close = function () {
                messageEvent.onClose();
            }
            return this;
        };

    exports('websocket', websocket);

});